package com.heima.app.gateway.filter;


import com.heima.app.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局过滤器,校验jwt令牌并且解析令牌,然后发送到各个微服务中
 */


@Component
@Slf4j
@Order(1)
public class AuthorizeFilter implements GlobalFilter {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取request和response对象,获取url,如果是登录请求就放行

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String url = request.getURI().getPath();
        if(url.contains("/login")){
           return chain.filter(exchange);
        }

        //从header中获取token,判断token是否存在
        String token = request.getHeaders().getFirst("token");
        if(StringUtils.isBlank(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        try {
            //如果存在,校验token
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int i = AppJwtUtil.verifyToken(claims);
            //校验是否有效,-1,0 有效  1,2 过期
            if(i>0){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }

            //有效,解析token,取出id
//            Integer id = claims.get("id",Integer.class);
            Integer id = claims.get("id",Integer.class);

//            if(id==null){
//                response.setStatusCode(HttpStatus.UNAUTHORIZED);
//                return response.setComplete();
//            }

            //下放到各个微服务
            ServerHttpRequest httpRequest = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", id.toString());
            }).build();

            exchange.mutate().request(httpRequest).build();

        } catch (Exception e) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        return chain.filter(exchange);
    }
}
